package com.lx.constant.segment.query;

import cn.hutool.core.util.StrUtil;
import com.lx.common.utils.CommonClassUtil;
import com.lx.constant.consts.CommonConstant;
import com.lx.constant.enums.SortWayEnum;
import com.lx.constant.segment.Segment;
import com.lx.wrapper.AbstractWrapper;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.Column;
import javax.persistence.Id;
import java.lang.reflect.Field;

/**
 * 排序语句
 *
 * @author lx
 * @create 2022/11/14 22:44
 **/
@Getter
@Setter
public class OrderSegment extends Segment {

    /**
     * 排序方式
     */
    private SortWayEnum sortWay;

    @Override
    public String convertSegmentToQL(AbstractWrapper parentWrapper, AbstractWrapper thisWrapper, boolean isHQL) {
        String columnName = super.convertSegmentToQL(parentWrapper, thisWrapper, isHQL);
        if (columnName == null) {
            return null;
        }
        return columnName + sortWay.getWay();
    }

    @Override
    public String getColumnNameBySegment(boolean isHQL) {
        String originColumnName = super.getColumnNameBySegment(isHQL);
        if (StrUtil.isEmpty(originColumnName)) {
            return originColumnName;
        }
        if (!isHQL) {
            //SQL获取的列名则直接返回
            return originColumnName;
        }
        Field columnField = getColumnField();
        if (columnField == null) {
            return originColumnName;
        }
        //当HQL语句获取列名时, 可能需要特殊扩展
        Field idColumnField = CommonClassUtil.findAnnotationFieldFromClass(columnField.getType(), Id.class, Column.class);
        if (idColumnField == null) {
            return originColumnName;
        }
        return originColumnName + CommonConstant.POINT + idColumnField.getAnnotation(Column.class).name();
    }

}
